
import axios from 'axios'
import moment from 'moment'
import { policy } from '@/api/aliyunApi'

//文件扩展名提取
export function fileType(fileName) {
    return fileName.substring(fileName.lastIndexOf('.') + 1)
}

// /**
//  * oss路径定义
//  * @param file
//  */
// export function ossPath(file) {
//     const folder = moment().format('YYYY-MM-DD')
//     if (file.name) {
//         return `admin/${folder}/${fileType(file.name)}/${file.name}`
//     } else {
//         return `admin/${folder}/html/${moment().format('YYYY-MM-DD-HH-mm-ss')}.html`
//     }
// }

export function ossUpload(file) {
    return new Promise((resolve, reject) => {
        policy().then(res => {
            const formData = new FormData()
            const dir = res.data.dir + res.data.filename  + '.'+fileType(file.name)
            formData.append('key', dir)
            formData.append('ossaccessKeyId', res.data.accessid)
            formData.append('policy',  res.data.policy)
            formData.append('signature', res.data.signature)
            formData.append('success_action_status', '200')
            formData.append('dir',res.data.dir)
            formData.append('host',res.data.host)
            formData.append('file', file)
            const imgUrl = res.data.host +"/" + dir
            axios.post("https://bit-litao.oss-cn-hangzhou.aliyuncs.com", formData).then((res) => {
                const { status } = res
                if (status === 200) {
                    const data = {
                        url: imgUrl,
                        type: file.name ? fileType(file.name) : 'html'
                    }
                    resolve(data)
                } else {
                    reject(res)
                }
            }).catch(err => {
                reject(err)
            })
        })
    }).catch(err => { })
}